import os
import json
import re
from datetime import datetime
from typing import Dict, List, Any
from django.conf import settings
from utils.baidu_ai import baidu_ai
import openai


class ResumeAnalyzer:
    """简历分析服务类"""
    
    def __init__(self):
        self.supported_formats = ['.pdf', '.docx', '.doc', '.txt', '.jpg', '.jpeg', '.png']
    
    def analyze_resume(self, file_path: str, original_filename: str) -> Dict[str, Any]:
        """
        分析简历文件
        Args:
            file_path: 文件路径
            original_filename: 原始文件名
        Returns:
            分析结果字典
        """
        try:
            # 1. 提取文本内容
            extracted_text = self._extract_text(file_path, original_filename)
            
            # 2. 分析简历内容（结构化）
            analysis_result = self._analyze_content(extracted_text)
            
            # 3. 用大模型AI生成建议和推荐，并打印详细日志
            ai_result = self.get_ali_qwen_analysis(extracted_text)
            print("AI原始返回：", ai_result)
            try:
                ai_json = json.loads(ai_result)
                print("AI解析后：", ai_json)
                improvement_suggestions = ai_json.get("improvement_suggestions", [])
                recommended_positions = ai_json.get("recommended_positions", [])
                recommended_companies = ai_json.get("recommended_companies", [])
            except Exception as e:
                print("AI解析异常：", e)
                improvement_suggestions, recommended_positions, recommended_companies = [], [], []
            
            return {
                'success': True,
                'extracted_text': extracted_text,
                'analysis_result': analysis_result,
                'improvement_suggestions': improvement_suggestions,
                'recommended_positions': recommended_positions,
                'recommended_companies': recommended_companies
            }
            
        except Exception as e:
            return {
                'success': False,
                'error': str(e)
            }
    
    def _extract_text(self, file_path: str, filename: str) -> str:
        """提取文件中的文本内容"""
        file_ext = os.path.splitext(filename)[1].lower()
        
        if file_ext in ['.jpg', '.jpeg', '.png']:
            # 图片文件，使用OCR识别
            return self._extract_text_from_image(file_path)
        elif file_ext == '.pdf':
            # PDF文件
            return self._extract_text_from_pdf(file_path)
        elif file_ext in ['.docx', '.doc']:
            # Word文档
            return self._extract_text_from_word(file_path)
        elif file_ext == '.txt':
            # 文本文件
            return self._extract_text_from_txt(file_path)
        else:
            raise ValueError(f"不支持的文件格式: {file_ext}")
    
    def _extract_text_from_image(self, file_path: str) -> str:
        """从图片中提取文本（使用百度AI OCR）"""
        try:
            ocr_result = baidu_ai.ocr_text_recognition(file_path)
            if ocr_result['success']:
                words_list = ocr_result['data']['words_list']
                return '\n'.join(words_list)
            else:
                raise Exception(f"OCR识别失败: {ocr_result.get('error_msg', '未知错误')}")
        except Exception as e:
            raise Exception(f"图片文本提取失败: {str(e)}")
    
    def _extract_text_from_pdf(self, file_path: str) -> str:
        """从PDF中提取文本"""
        try:
            import PyPDF2
            with open(file_path, 'rb') as file:
                pdf_reader = PyPDF2.PdfReader(file)
                text = ""
                for page in pdf_reader.pages:
                    text += page.extract_text() + "\n"
                return text
        except ImportError:
            raise Exception("需要安装PyPDF2库来处理PDF文件")
        except Exception as e:
            raise Exception(f"PDF文本提取失败: {str(e)}")
    
    def _extract_text_from_word(self, file_path: str) -> str:
        """从Word文档中提取文本"""
        try:
            from docx import Document
            doc = Document(file_path)
            text = ""
            for paragraph in doc.paragraphs:
                text += paragraph.text + "\n"
            return text
        except ImportError:
            raise Exception("需要安装python-docx库来处理Word文档")
        except Exception as e:
            raise Exception(f"Word文档文本提取失败: {str(e)}")
    
    def _extract_text_from_txt(self, file_path: str) -> str:
        """从文本文件中提取文本"""
        try:
            with open(file_path, 'r', encoding='utf-8') as file:
                return file.read()
        except UnicodeDecodeError:
            try:
                with open(file_path, 'r', encoding='gbk') as file:
                    return file.read()
            except Exception as e:
                raise Exception(f"文本文件读取失败: {str(e)}")
        except Exception as e:
            raise Exception(f"文本文件读取失败: {str(e)}")
    
    def _analyze_content(self, text: str) -> Dict[str, Any]:
        """分析简历内容"""
        analysis = {
            'basic_info': self._extract_basic_info(text),
            'education': self._extract_education(text),
            'work_experience': self._extract_work_experience(text),
            'skills': self._extract_skills(text),
            'projects': self._extract_projects(text),
            'languages': self._extract_languages(text),
            'certificates': self._extract_certificates(text),
            'summary': self._generate_summary(text)
        }
        return analysis
    
    def _extract_basic_info(self, text: str) -> Dict[str, str]:
        """提取基本信息"""
        info = {}
        
        # 提取姓名
        name_patterns = [
            r'姓名[：:]\s*([^\n\r]+)',
            r'([^\n\r]{2,4})\s*简历',
            r'([^\n\r]{2,4})\s*个人简历'
        ]
        for pattern in name_patterns:
            match = re.search(pattern, text)
            if match:
                info['name'] = match.group(1).strip()
                break
        
        # 提取电话
        phone_pattern = r'1[3-9]\d{9}'
        phone_match = re.search(phone_pattern, text)
        if phone_match:
            info['phone'] = phone_match.group()
        
        # 提取邮箱
        email_pattern = r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}'
        email_match = re.search(email_pattern, text)
        if email_match:
            info['email'] = email_match.group()
        
        # 提取年龄/出生日期
        age_patterns = [
            r'年龄[：:]\s*(\d+)',
            r'出生[：:]\s*(\d{4}[-/]\d{1,2}[-/]\d{1,2})',
            r'(\d{4}[-/]\d{1,2}[-/]\d{1,2})'
        ]
        for pattern in age_patterns:
            match = re.search(pattern, text)
            if match:
                info['birth_date'] = match.group(1)
                break
        
        return info
    
    def _extract_education(self, text: str) -> List[Dict[str, str]]:
        """提取教育经历"""
        education = []
        
        # 查找教育经历部分
        edu_section_patterns = [
            r'教育经历[：:](.*?)(?=工作经历|项目经历|技能|$)',
            r'教育背景[：:](.*?)(?=工作经历|项目经历|技能|$)',
            r'学历[：:](.*?)(?=工作经历|项目经历|技能|$)'
        ]
        
        for pattern in edu_section_patterns:
            match = re.search(pattern, text, re.DOTALL)
            if match:
                edu_text = match.group(1)
                # 解析具体的教育信息
                schools = re.findall(r'([^\n\r]+大学|[^\n\r]+学院|[^\n\r]+学校)', edu_text)
                majors = re.findall(r'专业[：:]\s*([^\n\r]+)', edu_text)
                degrees = re.findall(r'(本科|硕士|博士|大专|高中)', edu_text)
                
                for i, school in enumerate(schools):
                    edu_item = {'school': school}
                    if i < len(majors):
                        edu_item['major'] = majors[i]
                    if i < len(degrees):
                        edu_item['degree'] = degrees[i]
                    education.append(edu_item)
                break
        
        return education
    
    def _extract_work_experience(self, text: str) -> List[Dict[str, str]]:
        """提取工作经历"""
        work_experience = []
        
        # 查找工作经历部分
        work_section_patterns = [
            r'工作经历[：:](.*?)(?=教育经历|项目经历|技能|$)',
            r'工作经验[：:](.*?)(?=教育经历|项目经历|技能|$)',
            r'工作履历[：:](.*?)(?=教育经历|项目经历|技能|$)'
        ]
        
        for pattern in work_section_patterns:
            match = re.search(pattern, text, re.DOTALL)
            if match:
                work_text = match.group(1)
                # 解析具体的工作信息
                companies = re.findall(r'([^\n\r]+公司|[^\n\r]+集团|[^\n\r]+科技)', work_text)
                positions = re.findall(r'职位[：:]\s*([^\n\r]+)', work_text)
                durations = re.findall(r'(\d{4}[-/]\d{1,2}[^\n\r]*\d{4}[-/]\d{1,2})', work_text)
                
                for i, company in enumerate(companies):
                    work_item = {'company': company}
                    if i < len(positions):
                        work_item['position'] = positions[i]
                    if i < len(durations):
                        work_item['duration'] = durations[i]
                    work_experience.append(work_item)
                break
        
        return work_experience
    
    def _extract_skills(self, text: str) -> List[str]:
        """提取技能"""
        skills = []
        
        # 查找技能部分
        skill_patterns = [
            r'技能[：:](.*?)(?=教育经历|工作经历|项目经历|$)',
            r'技术栈[：:](.*?)(?=教育经历|工作经历|项目经历|$)',
            r'专业技能[：:](.*?)(?=教育经历|工作经历|项目经历|$)'
        ]
        
        for pattern in skill_patterns:
            match = re.search(pattern, text, re.DOTALL)
            if match:
                skill_text = match.group(1)
                # 提取技能关键词
                skill_keywords = [
                    'Python', 'Java', 'JavaScript', 'C++', 'C#', 'PHP', 'Ruby', 'Go', 'Rust',
                    'HTML', 'CSS', 'React', 'Vue', 'Angular', 'Node.js', 'Django', 'Flask',
                    'Spring', 'MySQL', 'PostgreSQL', 'MongoDB', 'Redis', 'Docker', 'Kubernetes',
                    'AWS', 'Azure', 'GCP', 'Linux', 'Git', 'Jenkins', 'Jira', 'Agile',
                    '机器学习', '深度学习', '数据分析', '数据挖掘', '人工智能', '自然语言处理',
                    '计算机视觉', '大数据', '云计算', '微服务', 'API', 'RESTful'
                ]
                
                for skill in skill_keywords:
                    if skill.lower() in skill_text.lower():
                        skills.append(skill)
                break
        
        return list(set(skills))  # 去重
    
    def _extract_projects(self, text: str) -> List[Dict[str, str]]:
        """提取项目经历"""
        projects = []
        
        # 查找项目经历部分
        project_patterns = [
            r'项目经历[：:](.*?)(?=教育经历|工作经历|技能|$)',
            r'项目经验[：:](.*?)(?=教育经历|工作经历|技能|$)',
            r'项目[：:](.*?)(?=教育经历|工作经历|技能|$)'
        ]
        
        for pattern in project_patterns:
            match = re.search(pattern, text, re.DOTALL)
            if match:
                project_text = match.group(1)
                # 简单的项目名称提取
                project_names = re.findall(r'([^\n\r]+系统|[^\n\r]+平台|[^\n\r]+应用)', project_text)
                for name in project_names:
                    projects.append({'name': name})
                break
        
        return projects
    
    def _extract_languages(self, text: str) -> List[str]:
        """提取语言能力"""
        languages = []
        
        # 查找语言能力部分
        language_patterns = [
            r'语言能力[：:](.*?)(?=教育经历|工作经历|技能|$)',
            r'外语[：:](.*?)(?=教育经历|工作经历|技能|$)'
        ]
        
        for pattern in language_patterns:
            match = re.search(pattern, text, re.DOTALL)
            if match:
                language_text = match.group(1)
                language_keywords = ['英语', '日语', '韩语', '法语', '德语', '西班牙语', '俄语']
                for lang in language_keywords:
                    if lang in language_text:
                        languages.append(lang)
                break
        
        return languages
    
    def _extract_certificates(self, text: str) -> List[str]:
        """提取证书"""
        certificates = []
        
        # 查找证书部分
        cert_patterns = [
            r'证书[：:](.*?)(?=教育经历|工作经历|技能|$)',
            r'资格认证[：:](.*?)(?=教育经历|工作经历|技能|$)'
        ]
        
        for pattern in cert_patterns:
            match = re.search(pattern, text, re.DOTALL)
            if match:
                cert_text = match.group(1)
                cert_keywords = ['PMP', 'PMP认证', 'CISSP', 'CCNA', 'CCNP', 'AWS认证', 'Azure认证']
                for cert in cert_keywords:
                    if cert in cert_text:
                        certificates.append(cert)
                break
        
        return certificates
    
    def _generate_summary(self, text: str) -> Dict[str, Any]:
        """生成简历摘要"""
        summary = {
            'total_words': len(text),
            'has_contact_info': bool(re.search(r'1[3-9]\d{9}', text) or re.search(r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}', text)),
            'has_education': bool(re.search(r'教育经历|教育背景|学历', text)),
            'has_work_experience': bool(re.search(r'工作经历|工作经验|工作履历', text)),
            'has_skills': bool(re.search(r'技能|技术栈|专业技能', text)),
            'has_projects': bool(re.search(r'项目经历|项目经验|项目', text))
        }
        return summary
    
    def get_ali_qwen_analysis(self, resume_text):
        client = openai.OpenAI(
            api_key=os.getenv("DASHSCOPE_API_KEY"),
            base_url="https://dashscope.aliyuncs.com/compatible-mode/v1"
        )
        prompt = f"""
你是一名资深职业顾问，请根据以下简历内容，分析候选人的不足，并给出3条具体的改进建议，以及3个适合他的职位推荐和3家适合的公司推荐，输出格式为JSON，字段为improvement_suggestions、recommended_positions、recommended_companies。
简历内容：
{resume_text}
        """
        completion = client.chat.completions.create(
            model="qwen-plus",
            messages=[
                {"role": "system", "content": "You are a helpful assistant."},
                {"role": "user", "content": prompt}
            ]
        )
        return completion.choices[0].message.content


# 创建全局实例
resume_analyzer = ResumeAnalyzer() 